package org.dut.community.util;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MailClient {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String content) {
        try{
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            mimeMessageHelper.setFrom(from); // 谁来发
            mimeMessageHelper.setTo(to); // 发给谁
            mimeMessageHelper.setSubject(subject); // 主题
            mimeMessageHelper.setText(content, true); // 内容，支持html格式
            mailSender.send(mimeMessage);
        }catch(MessagingException e){
            log.error("发送邮件失败，失败原因: {}",e.getMessage());
        }
    }
}
